//
//  LBSoftlightColorFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 3/29/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBSoftlightColorFilter.h"
#include "LBGraphics.h"

char fShaderStrSoftlightColor[] = ""
"precision mediump float;"

"varying vec2 vtexCoor;"
"varying vec4 vposition;"
"uniform sampler2D texture;"
"uniform vec4 color;"
"uniform float opacity;"


// soft light function (opacity equal 1/2 value in photoshop)
"vec4 softLight(vec4 base, vec4 blend, float opacity){"
"   vec4 white = vec4(1.0, 1.0, 1.0, 1.0);"
"   vec4 lumCoeff = vec4(0.2125, 0.7154, 0.0721, 1.0);"
"   vec4 result;"

"   float luminance = dot(base, lumCoeff);"
"   if (luminance < 0.45)"
"       result = 2.0 * blend * base;"
"   else if (luminance > 0.55)"
"       result = white - 2.0 * (white - blend) * (white - base);"
"   else"
"   {"
"       vec4 result1 = 2.0 * blend * base;"
"       vec4 result2 = white - 2.0 * (white - blend) * (white - base);"
"       result = mix(result1, result2, (luminance - 0.45) * 10.0);"
"   }"
"    result = mix(base, result, opacity);"
"   return result;"
"}"
// END soft light function


"void main()"
"{"
"    lowp vec4 textureColor = texture2D(texture, vtexCoor);"
"    textureColor = softLight(textureColor, color, opacity);"
"    gl_FragColor = textureColor;"
"}";

LBSoftlightColorFilter::LBSoftlightColorFilter(){
    init(0, fShaderStrSoftlightColor);
    LBGraphics::getInstance()->useProgram(program);
    colorUniform = program->uniformIndex("color");
    opacityUniform = program->uniformIndex("opacity");
    setColor(1.0f, 1.0f, 1.0f);
    setOpactiy(1.0f);
}